package com.zzw.basic.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOClient implements Runnable{

    private Selector selector = null;
    private SocketChannel channel = null;
    private InetSocketAddress address = new InetSocketAddress("localhost", 8080);
    private ByteBuffer rcBuffer = ByteBuffer.allocate(1024);
    private ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
    private Integer i;

    public NIOClient(Integer i) throws IOException {
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(address);
        selector = Selector.open();
        channel.register(selector, SelectionKey.OP_CONNECT);
        this.i = i;
    }

    public void session() throws IOException {
        if (channel.isConnectionPending()) {
            channel.finishConnect();
            channel.register(selector,SelectionKey.OP_WRITE);
            System.out.println("客户端初始化完成");
        }
        //Scanner scan = new Scanner(System.in);
        /*while(scan.hasNext()){
            String name = scan.nextLine();
            if("".equals(name)){
                continue;
            }
            if("finish".equals(name)){
                System.exit(0);
            }*/
            process("hello" + i);
        //}
    }

    private void process(String name) throws IOException {
        boolean waitHelp = true;
        Iterator<SelectionKey> iterator = null;
        Set<SelectionKey> keys = null;
        while(selector.select() > 0){
            try {
                //int readys = selector.select();
                /*if(readys == 0){
                    System.out.println("**********");
                    continue;
                }*/
                keys = selector.selectedKeys();
                iterator = keys.iterator();
                while(iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if(key.isValid() && key.isWritable()){
                        sendBuffer.clear();
                        sendBuffer.put(name.getBytes());
                        sendBuffer.flip();
                        channel.write(sendBuffer);
                        channel.register(selector,SelectionKey.OP_READ);
                    }
                    else if(key.isValid() && key.isReadable()){
                        rcBuffer.clear();
                        int len = channel.read(rcBuffer);
                        if(len > 0){
                            System.out.println("收到消息：" + new String(rcBuffer.array()));
                            waitHelp = false;
                        }
                        channel = (SocketChannel) key.channel();
                        //channel.register(selector,SelectionKey.OP_WRITE);
                    }
                    iterator.remove();
                }
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    for (SelectionKey key:keys){
                        key.cancel();
                    }
                    channel.socket().close();
                    channel.close();
                    return;
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        for (int i = 0;i < 1;i++){
            Thread.sleep(500);
            new Thread(new NIOClient(i)).start();
        }
    }

    @Override
    public void run() {
        try {
            session();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
